<!-- Progress进度认证 -->
<template>
  <div class="container-progress">
    <van-nav-bar title="进度认证"  @click-left="goBack" v-if="$route.path !== '/integration'">
      <span class="el-icon-arrow-left fontsize" slot="left"></span>
    </van-nav-bar>

    <div class="wrapper">
      <van-cell-group v-if="isFast">
        <van-field
          placeholder="请选择楼栋"
          label="楼栋："
          :right-icon="isFast?'arrow':''"
          disabled
          v-model.trim="floor"
          @click-right-icon="choiceFloor"
        />
      </van-cell-group>

      <van-cell-group class="task">
        <van-field
          placeholder="作业任务"
          label="作业任务："
          :right-icon="isFast?'arrow':''"
          disabled
          v-model.trim="task"
          @click-right-icon="choiceTask"
        />
      </van-cell-group>

      <van-cell-group class="schedule">
        <van-field placeholder="请输入进度百分比" label="任务进度：" :disabled="!btnShow" v-model.trim="schedule"/>
      </van-cell-group>

      <van-cell-group>
        <van-field
          v-model.trim="currentDateToString"
          label="日期"
          :right-icon="btnShow?'arrow':''"
          placeholder="请选择日期"
          :disabled="!btnShow"
          @click-right-icon="choiceTime"
        />

      </van-cell-group>
    </div>

    <van-popup v-model="floor_show" position="bottom" :close-on-click-overlay="true" class="iPopup">
      <van-picker
        show-toolbar
        title="楼栋"
        :columns="floor_columns"
        @cancel="onFloorCancel"
        @confirm="onFloorConfirm"
      />
    </van-popup>

    <van-popup v-model="task_show" position="bottom" class="iPopup">
      <van-picker
        show-toolbar
        title="作业任务"
        :columns="task_columns"
        @cancel="onTaskCancel"
        @confirm="onTaskConfirm"
      />
    </van-popup>
    <van-popup v-model="time_show" position="bottom" class="iPopup">
      <van-datetime-picker
        type="date"
        @cancel="onTimeCancel"
        @confirm="onTimekConfirm"
      />
    </van-popup>
    <div class="wrapper-upload">
      <div class="upload-title">上传照片</div>
      <div class="upload-file" >
        <template v-if="imgList1.length">
          <div v-for="(item,index) in imgList1" :key="index" class="upload-file-box" @click="deletePoto(index)">
          <img :src="item" />
        </div> 
        </template>
        <div v-if="imgList1.length< 2 && btnShow" class="upload-file-box" @click="selectPhoto" v-loading="uploading">
          <van-icon name="plus"/>
        </div>  
        <span v-show="btnShow" class="upload-txt">最多上传2张</span>
      </div>
    </div>

    <van-row class="progress-btn">
      <van-col span="22" offset="1">
        <van-button v-show="btnShow" type="info" size="large" @click="saveConfirm()">确认</van-button>
      </van-col>
    </van-row>

    <!-- <van-actionsheet
      v-model="phone_show"
    >
    <van-uploader capture="camera" :after-read="onRead" accept="image/*" :max-size="8388608" @oversize="oversize" class="upload-file-item">
      <div>
        拍摄
      </div>
    </van-uploader>
    <van-uploader :after-read="onRead" accept="image/*" :max-size="8388608" @oversize="oversize" class="upload-file-item">
      <div>
        从手机相册选择
      </div>
    </van-uploader>
    <div class="upload-file-item cancel" @click="uploadCancel">
      取消
    </div>
    </van-actionsheet> -->
    <van-actionsheet
    v-model="phone_show"
    :actions="photoActions"
    cancel-text="取消"
    @select="onPicSelect" 
    @cancel="phone_show = false"
    />
  </div>
</template>

<script type='textecmascript-6'>
import {GetBuilding,
GetACSchedulePlanCbxAPP,
AddModelAuthentication,
GetAuthenticationInfoByTaskId,
UploadBase64Img
} from '@/api/api.js'
import Camera from '@/common/Camera/Camera.js'

export default {
  mixins: [Camera],
  data() {
    return {
      data: "Progress进度认证",
      dialogImageUrl: "",
      photoActions: [
        {
          id: 0,
          name: '拍照'
        },
        {
          id: 1,
          name: '从手机相册选择'
        }
      ],
      dialogVisible: false,
      floor_show: false,
      task_show: false,
      time_show: false,
      phone_show: false,
      floor_columns: [],
      task_columns: [],
      floor: "", //当前楼栋
      task: "", //当前任务
      TaskId: '',  //任务ID
      schedule: "", //当前进度
      currentDate: new Date(), //当前时间
      projectid: localStorage.getItem('projectid'),
      userId: parseInt(localStorage.getItem('userId')),
      isFast: false, //是否从首页快捷跳转过来 是:true, 否：false
      paramsData: {}, //保存路由参数对象
      imgList1: [],
      UploadTime: '',  //保存获取默认认证时间
      isNew: false,   //是否新增
      uploading: false,
      btnShow: true
    };
  },
  created(){
    this.getParams()
    this.getBuildingInfo(this.projectid)
    
  },
  mounted () {
    if (this.$route.path === '/integration') {
      this.imgList1.push(this.$parent.imgData.TokenUrL + this.$parent.imgData.smallPhotoURL)
    }
  },
  computed: {
    currentDateToString(){
      console.log(this.isFast)
      console.log(this.isNew)
      if(!this.isFast&&!this.isNew){
        console.log(this.UploadTime)
        return this.UploadTime.substr(0, 10)
      } else {
        console.log(require('moment')(this.currentDate).format('YYYY-MM-DD'))
        return require('moment')(this.currentDate).format('YYYY-MM-DD')
      }
      
    }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /**
     * van-popup  显示/隐藏操作
     */
    choiceFloor() {
      if(!this.isFast){
        return
      }
      if (!this.floor_show) {
        this.floor_show = true;
      } else {
        this.floor_show = false;
      }
    },
    choiceTask() {
      if(!this.isFast){
        return
      }
      if (!this.task_show && this.task_columns.length) {
        this.task_show = true;
      } else {
        this.task_show = false;
      }
    },
    choiceTime() {
      if(!this.time_show) {
        this.time_show = true
      } else {
        this.time_show = false
      }
    },
    selectPhoto(){
      if(!this.phone_show){
        this.phone_show = true
      }else {
        this.phone_show = false
      }
    },
    uploadCancel(){
      this.phone_show = false
    },
    // 获取参数函数
    getParams(){
      console.log(this.$route.query)
      let flag = this.$route.query.TaskId?true:false
      // console.log(flag)
      if(flag){
        this.floor = this.$route.query.BuildingName?this.$route.query.BuildingName: ' '
        this.task = this.$route.query.TaskName
        this.TaskId = this.$route.query.TaskId
        this.paramsData = this.$route.query
        if(this.paramsData.StatesInfo.indexOf('完成') > -1){
          this.btnShow = false
        }
        if(this.paramsData.StatesInfo === '未开始'){
          this.isNew = true
        } else {
          this.AuthenticationInfoByTaskId(this.TaskId)
        }
      }else {
        this.isFast = true
        this.isNew = true
      }
    },
    // 确认保存
    saveConfirm(){
      //校验
      if(this.floor == ''){
        this.$toast({
          message: '请选择楼栋!',
          duration: 1200,
          className: 'my-toast'
        })
        return
      }
      if(this.task == ''){
        this.$toast({
          message: '请选择作业任务!',
          duration: 1200,
          className: 'my-toast'
        })
        return
      }
      if(this.task === '暂无数据'){
         this.$toast({
          message: '暂无数据，无法认证！',
          duration: 1200,
          className: 'my-toast'
        })
        return
      }
      if(this.schedule == '') {
        this.$toast({
          message: '任务进度不能为空!',
          duration: 1200,
          className: 'my-toast'
        })
        return
      }
      this.GetAddModelAuthentication()
    },
    /**
     * 选择楼栋
     */
    onFloorConfirm(value,index) {
      console.log(value)
      console.log(index)
      // Toast(`当前值：${value}, 当前索引：${index}`);
      // this.$toast(`当前值：${value}, 当前索引：${index}`);
      this.floor = value.text;
      this.task = '';
      this.task_columns = [];
      this.floor_show = false;
    },
    onFloorCancel() {
      this.floor_show = false;
    },
    /**
     * 选择作业任务
     */
    onTaskConfirm(value) {
      this.task = value.text;
      this.TaskId = value.id;
      console.log(this.TaskId)
      this.task_show = false;
    },
    onTaskCancel() {
      this.task_show = false;
    },
    /**
     * @name 文件大小超过限制时触发
     * @param {Object} file 文件解析后的 file 对象
     */
    oversize(file){
      this.$toast({
        message: "文件大小不要超过1M",
        className: "my-toast"
      });
    },
    //删除照片
   deletePoto(index){
     if(this.btnShow){
      this.$dialog.confirm({
        title: '删除确认',
        message: '确认删除吗？',
        className: 'deletePhoto'
      }).then(() => {
        // on confirm
        this.imgList1.splice(index, 1)
      }).catch(() =>{
        // on cancel
      })
     }
     
   },
   onPicSelect(item){
     switch(item.id){
       case 0:
         {
           this.uploading = true;
           this.captureImage().then(res=>{
             console.log(res)
             let url = res[0].TokenUrL + res[0].smallPhotoURL 
             this.imgList1.push(url)
           })
           this.uploading = false;
         }
         break;
       case 1:
         {
           this.uploading = true;
            this.gettingAlbums().then(res => {
              console.log(res)
              let url = res[0].TokenUrL + res[0].smallPhotoURL 
              this.imgList1.push(url)
              // this.photoList = res;
            })
            this.uploading = false;
         }
         break;
       default:
         break;
     }
   },
    async onRead(file) {
      console.log(file);
      this.phone_show = false
      let params = {
        Base64Photo: file.content,
        fileext: file.file.name
      }
      let res = await this.Request(UploadBase64Img(params))
      console.log(res)
      if(res.StatusCode === 200){
        let url = res.Detiel[0].TokenUrL+res.Detiel[0].smallPhotoURL
        this.imgList1.push(url)

      }else {
        this.$message({
          type: 'error',
          message: res.Message,
          center: 'true'
        })
      }
    },
    goBack(){
        this.$router.go(-1);
    },
    /**
     * 选择日期
     */
    onTimekConfirm(value){
      console.log(value)
      if(!this.isNew) {
        this.UploadTime = require('moment')(value).format('YYYY-MM-DD')
        this.time_show = false
        console.log(this.UploadTime)
        return false
      }
      this.currentDate = value
      console.log(this.currentDate)
      this.time_show = false
    },
    onTimeCancel() {
      this.time_show = false
    },
    /**
     * api接口
     */
    //获取楼栋信息
    async getBuildingInfo(projectid){
      console.log(this.isFast)
      if(!this.isFast){
        return false
      }
      let res = await this.Request(GetBuilding({projectid}))
      console.log(res)
      if(res.StatusCode === 200){
        this.floor_columns = res.Detiel
      }else {
        this.$message({
          type: 'error',
          message: res.Message,
          center: 'true'
        })
      }
    },
    // 根据楼栋筛选认证任务下拉
    async ACSchedulePlanCbxAPP(ProjectID, BuildingName){
      let res = await this.Request(GetACSchedulePlanCbxAPP({ProjectID, BuildingName}))
      console.log(res)
      if(res.StatusCode === 200){
        if(res.Detiel.length){
          this.task_columns = res.Detiel
        } else {
          this.task = res.Message
        }
        
      }else {
        this.$message({
          type: 'error',
          message: res.Message,
          center: 'true'
        })
      }

    },
      /**
       * 认证
       */
      async GetAddModelAuthentication () {
       
        let upTime = ''
        if(!this.isNew) {
          upTime = this.UploadTime
        }else {
          upTime = this.currentDate
        }
        let nowTime = new Date()
        let nTime = new Date(upTime).toLocaleDateString().replace(/\//g, "-");
          let data = { 
          TaskId: this.TaskId,
          Percentage: this.schedule, 
          PicturePath: '', 
          UploadTime: nTime + " " + nowTime.getHours() + ":" + nowTime.getMinutes() + ":" + nowTime.getSeconds(), 
          userId: this.userId
          }
         if (this.imgList1.length) {
          //  获取URL
          //  let URL = `${this.imgList1[0].url},${this.imgList1[1]}`
          let URL = []
          this.imgList1.forEach((item) => {
            // URL += `${item.url},`
            let len = item.indexOf('U')
            let url = item.substring(len - 1)
            URL.push(url)
          })
          // URL = URL.substr(0, (URL.length - 1))
          data.PicturePath = URL.toString()
        }
        let res = await this.Request(AddModelAuthentication(data))
        if (res.StatusCode === 200) {
          this.$toast.success({ message: res.Message, duration: 2000,className: 'my_toast_success' })
          setTimeout(()=>{
            this.$router.go(-1)
          }, 2000)
        } else {
          this.$toast.fail({ message: res.Message, duration: 2000,className: 'my_toast_fail' })
        }
      },
      /**
       * 查询认证详情
       */
      async AuthenticationInfoByTaskId (id) {
        if (!id) return this.$toast('传入数据有误')
        let res = await this.Request(GetAuthenticationInfoByTaskId({ TaskId: id }))
        console.log(res)
        if (res.StatusCode === 200) {
          let imgObj = res.Detiel[0].PicturePath
          if (imgObj) {
            this.imgList1 = imgObj.split(',')
            // this.showImg = []
            // this.imgList1.forEach(item => {
            //   this.showImg.push({
            //     name: '',
            //     url: item
            //   })
            // })
          } else {
            this.imgList1 = []
            // this.showImg = []
          }
          this.schedule = res.Detiel[0].Percentage
            console.log(this.schedule)
          this.UploadTime = res.Detiel[0].UploadTime
          // this.dialogForm.name = res.Detiel[0].cName
          // this.dialogForm.progress = `${parseInt(res.Detiel[0].Percentage)}`
          // 将监听开关重置为false
          // this.isChange = false
        } else {
          this.$message({ type: 'error', message: res.Message, center: 'true' })
        }
      },
  },
  watch: {
    floor(val){
      if(this.isFast&&val){
        this.ACSchedulePlanCbxAPP(this.projectid, val)
      }
    }
  }
};
</script>
<style lang='stylus' scoped rel='stylesheet/stylus'>
.container-progress {
  width: 100%;
  height: 100%;
}
</style>


<style>
.container-progress .wrapper .task .van-field__label,
.container-progress .wrapper .schedule .van-field__label {
  max-width: 150px;
}
.container-progress .van-field__control {
  font-size:30px;
  font-family:SourceHanSansCN-Regular;
  font-weight:400;
  color:#333;
}
.container-progress .wrapper .van-field__right-icon .van-icon,
.upload-file-box .van-icon {
  font-size: 36px;
}
.deletePhoto.van-dialog {
  width: 50%!important;
  font-size: 32px;
}
/* Popup begin */
.iPopup .van-picker-column {
  font-size: 30px;
}
.iPopup .van-picker__cancel,
.iPopup .van-picker__confirm,
.iPopup .van-picker__title {
  font-size: 30px;
}
.iPopup .van-picker__toolbar {
  height: 88px;
  line-height: 88px;
}
/* Popup end */
.container-progress .van-cell .van-field__label span{
  font-weight: 600;
}
</style>

<style scoped>
.container-progress .van-nav-bar {
  height: 88px;
  line-height: 88px;
}
.container-progress .van-nav-bar__title {
  font-size: 36px;
}
.container-progress .van-nav-bar__left,
.container-progress .van-nav-bar__right {
  font-size: 42px;
}
.container-progress .wrapper .van-cell {
  font-size: 30px;
  line-height: 88px;
}
.container-progress .wrapper .van-hairline--top-bottom::after {
  left: -330px;
  right: -330px;
}
.wrapper-upload {
  padding: 20px;
}
.upload-txt {
  color: #999999;
  font-size: 26px;
  margin-left: 10px;
}
.upload-title {
  font-size: 30px;
  font-weight: 600;
  padding: 20px 0;
}
.upload-file {
  display: -webkit-flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: flex-end;
}
.upload-file-box {
  margin-right: 10px;
  width: 200px;
  height: 200px;
  border: 1px lightgray dashed;
  display: flex;
  justify-content: center;
  align-items: center;
}
.upload-file-box>img {
  width: 200px;
  height: 200px;
  border: none;
}

.upload-file-item {
  display: flex;
  justify-content: center;
  align-items: center;
  width:100%;
  height: 88px;
  font-size: 32px;
  color: #333;
}
.cancel {
  color: #666!important;
}
.progress-btn {
  margin-top: 100px;
}
.progress-btn .van-button--large {
  height: 88px;
  line-height: 88px;
  border-radius: 10px;
}
.progress-btn .van-button--large .van-button__text {
  font-size: 30px;
}
</style>

<style>
/* 顶部表头 */
  .container-progress .van-nav-bar .van-nav-bar__title {
    font-size: 36px;
    font-weight: 600;
  }
  .container-progress  .van-nav-bar {
    height: 88px;
    line-height: 88px;
  }
  .my_toast_success.van-toast {
    font-size: 30px;
  }
  .my_toast_success.van-toast--default{
      width: 180px;
      padding: 30px;
  }
  .my_toast_success.van-toast--text {
      padding: 40px 40px
  }
  .my_toast_success.van-toast--default .van-toast__icon{
      font-size: 96px;
  }
  /* toast begin */
.my-toast.van-toast {
    font-size: 30px;
}
.my-toast.van-toast--default{
    width: 180px;
    padding: 30px;
}
.my-toast.van-toast--text {
    padding: 40px 40px
}
.my-toast.van-toast--default .van-toast__icon{
    font-size: 96px;
}
/* toast end */
</style>
